package com.jingdianjichi.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.jingdianjichi.auth.application.convert.AuthUserDTOConverter;
import com.jingdianjichi.auth.entity.Result;
import com.jingdianjichi.auth.domain.entity.AuthUserBO;
import com.jingdianjichi.auth.domain.service.AuthUserDomainService;
import com.jingdianjichi.auth.entity.AuthUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;

    /**
     * 注册用户的个人信息
     * @return 返回用户是否注册成功
     */
    @RequestMapping("/register")
    public Result<Boolean> registry(@RequestBody AuthUserDTO authUserDto) {
        try {
            if(log.isInfoEnabled()){
                log.info("UserController.registry.dto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getUserName()),"用户账号不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getPassword()),"用户密码不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getEmail()),"邮件地址不能为空!");
            AuthUserBO authUserBO = AuthUserDTOConverter.instance.authUserDTOToBO(authUserDto);
            return Result.ok(authUserDomainService.registry(authUserBO));
        } catch (Exception e) {
            log.error("UserController.registry.error: {}",e.getMessage(),e);
            return Result.fail("注册用户失败");
        }

    }

    /**
     * 更新用户信息
     */
    @RequestMapping("/update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDto) {
        try {
            if(log.isInfoEnabled()){
                log.info("UserController.update.dto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getUserName()),"用户账号不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getPassword()),"用户密码不能为空!");
            AuthUserBO authUserBO = AuthUserDTOConverter.instance.authUserDTOToBO(authUserDto);
            return Result.ok(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.update.error: {}",e.getMessage(),e);
            return Result.fail("更新用户信息失败");
        }

    }

    /**
     * 获取用户信息详情
     */
    @RequestMapping("/getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDto) {
        try {
            if(log.isInfoEnabled()){
                log.info("UserController.getUserInfo.dto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getUserName()),"用户名不能为空!");
            AuthUserBO authUserBO = AuthUserDTOConverter.instance.authUserDTOToBO(authUserDto);
            AuthUserBO resultBO = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO authUserDTO = AuthUserDTOConverter.instance.authUserBOToDTO(resultBO);
            return Result.ok(authUserDTO);
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error: {}",e.getMessage(),e);
            return Result.fail("获取用户信息失败");
        }

    }

    /**
     * 删除用户信
     */
    @RequestMapping("/delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDto) {
        try {
            if(log.isInfoEnabled()){
                log.info("UserController.delete.authUserDto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkNotNull(authUserDto.getId(),"用户id不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.instance.authUserDTOToBO(authUserDto);
            return Result.ok(authUserDomainService.delete(authUserBO));
        } catch (Exception e) {
            log.error("UserController.delete.error: {}",e.getMessage(),e);
            return Result.fail("删除用户失败");
        }

    }

    /**
     * 用户启用禁用
     */
    @RequestMapping("/changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDto) {
        try {
            if(log.isInfoEnabled()){
                log.info("UserController.changeStatus.authUserDto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkNotNull(authUserDto.getId(),"用户id不能为空");
            Preconditions.checkNotNull(authUserDto.getStatus(),"用户状态不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.instance.authUserDTOToBO(authUserDto);
            return Result.ok(authUserDomainService.changeStatus(authUserBO));
        } catch (Exception e) {
            log.error("UserController.delete.error: {}",e.getMessage(),e);
            return Result.fail("状态更新失败");
        }

    }

    @RequestMapping("doLogin")
    public Result doLogin(@RequestParam("validCode") String validCode) {
        try {
            Preconditions.checkArgument(!StringUtils.isBlank(validCode),"验证码不能为空!");
            SaTokenInfo saTokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(saTokenInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("登录失败");
        }
    }

    /**
     * 用户退出登录
     */
    @RequestMapping("/logOut")
    public Result logOut(@RequestParam String username) {
        try {
            log.info("UserController.logOut.username: {}", username);
            Preconditions.checkArgument(StringUtils.isBlank(username),"用户名不能为空");
            StpUtil.logout(username);
            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.logOut.error: {}",e.getMessage(),e);
            return Result.fail("用户退出登录失败");
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }
    
}
